const express = require("express");
const router = express.Router();
const { db, genid } = require("../db/DbUtils");
const { v4: uuidv4 } = require("uuid");

router.post("/login", async (req, res) => {
  let { account, password } = req.body;
  let { err, rows } = await db.async.all(
    "select * from `admin` where `account` = ? AND `password` = ?",
    [account, password]
  );
  if (err == null && rows.length > 0) {
    // 生成token
    let login_token = uuidv4();
    let update_token_sql = "update `admin` SET `token` = ? where `id` = ?";
    const { id, account } = rows[0];

    const result = await db.async.run(update_token_sql, [login_token, id]);

    let admin_info = { id, account, login_token };

    res.send({
      code: 200,
      msg: "登录成功",
      data: admin_info,
    });
  } else {
    res.send({
      code: 500,
      msg: "登录失败",
    });
  }
});

module.exports = router;
